#ifndef PROTOCOL_HANDLER_HPP
#define PROTOCOL_HANDLER_HPP

#include <vector>
#include <string>
#include <nlohmann/json.hpp>
#include <cstdint>  // 新增：用于uint8_t等类型定义

// 缺陷类型枚举（8种）
enum class DefectType {
    MISSING_HOLE = 0,    // 漏孔
    MOUSE_BITE = 1,      // 鼠咬
    OPEN_CIRCUIT = 2,    // 开路
    SHORT = 3,           // 短路
    SPUR = 4,            // 毛刺
    SPURIOUS_COPPER = 5, // 杂铜
    PINHOLE = 6,         // 针孔
    SCRATCH = 7          // 划痕
};


// 控制动作枚举
enum class ControlAction {
    START, STOP, PAUSE, RESUME
};

// 服务器下发的控制消息结构
struct ControlMessage {
    std::vector<DefectType> defectTypes;      // Enabled defect types
    std::vector<int> slotMapping;             // 15-slot defect mapping
    ControlAction action;                     // Control action
    struct {
        std::string model;                    // Product model
        std::string batch;                    // Batch number
        std::string serial;                   // Serial number
    } productInfo;                            // Product information

    // Constructor
    ControlMessage() : action(ControlAction::START) {}
    
    // Parse from JSON
    static ControlMessage fromJson(const std::string& jsonStr);
    
    // Convert to JSON
    std::string toJson() const;
};

// 设备上报的检测结果消息结构
struct ReportMessage {
    std::string timestamp;                    // Timestamp (ISO 8601 format)
    bool hasDefects;                          // Whether defects exist
    struct {
        DefectType type;                      // Defect type
        float confidence;                     // Confidence (0-1)
        std::string location;                 // Location on PCB
    } defects[8];                             // Up to 8 defects
    int defectCount;                          // Actual defect count
    
    struct {
        int rack;                             // Rack number
        int slot;                             // Slot number
    } storageLocation;                        // Storage location
    
    struct {
        std::string thumbnail;                // Thumbnail (Base64 encoded)
        int width;                            // Image width (pixels)
        int height;                           // Image height (pixels)
        std::string format;                   // Image format (jpeg/png)
        int dataSize;                         // 新增：原始图像数据大小
        std::vector<uint8_t> rawData;         // 新增：原始图像数据（V4L2获取）
    } image;       
                               // Image information
    struct {
        std::string model;                    // Product model
        std::string batch;                    // Batch number
        std::string serial;                   // Serial number
    } productInfo;                           // Product information（新增）

    // Constructor
    ReportMessage() : defectCount(0), hasDefects(false) {}
    
    // Add a defect
    bool addDefect(DefectType type, float confidence, const std::string& location);
    
    // Parse from JSON
    static ReportMessage fromJson(const std::string& jsonStr);
    
    // Convert to JSON
    std::string toJson() const;
};

// 协议处理类
class ProtocolHandler {
public:
    // Singleton pattern
    static ProtocolHandler& getInstance();
    ProtocolHandler(const ProtocolHandler&) = delete;
    ProtocolHandler& operator=(const ProtocolHandler&) = delete;
    
    // Image processing - V4L2版本
    std::string imageToBase64(const std::vector<uint8_t>& rawData, int width, int height, 
                             const std::string& format, int quality = 80);
    std::vector<uint8_t> base64ToImage(const std::string& base64Str, int& width, int& height, 
                                     std::string& format);
    
    // Control message handling
    std::string encodeControlMessage(const ControlMessage& msg);
    ControlMessage decodeControlMessage(const std::string& jsonStr) const;
    
    // Report message handling
    std::string encodeReportMessage(const ReportMessage& msg);
    ReportMessage decodeReportMessage(const std::string& jsonStr);
    
private:
    ProtocolHandler() = default;
    ~ProtocolHandler() = default;
};

#endif // PROTOCOL_HANDLER_HPP